
function getRootPath(){
//	if(window.basePath ){ 
//		return window.basePath ;
//	}
    //获取当前网址，如： http://localhost:8083/uimcardprj/share/meun.jsp
    
    var curWwwPath=window.document.location.href;
    //获取主机地址之后的目录，如： uimcardprj/share/meun.jsp
    var pathName=window.document.location.pathname;
    var pos=curWwwPath.indexOf(pathName);
    //获取主机地址，如： http://localhost:8083
    var localhostPaht=curWwwPath.substring(0,pos);
    //获取带"/"的项目名，如：/uimcardprj
    var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
    return(localhostPaht+projectName);
}
function getUrl(){
	return window.document.location.href;
}
function getYuming(url){
	if(!url)return url;
	var yuming = url.replace("https://","").replace("http://","");
	var gengind = yuming.indexOf("/");
	yuming = yuming.substring(0,gengind > -1 ? gengind : yuming.length );
	return yuming;
}
var layer = {
	msg: (msg) => {
		
	},
	confirm: (msg,callback) => {
		
	},
	error: (msg)  => {
		
	},
	warn: (msg)  => {
		
	}
}

/**
 * <form lay-filter="test-form">
 * 		<input type="text" name="username">
 * 		<input type="radio" name="gender" value="male">
 * 		<input type="radio" name="gender" value="female">
 * 		<input type="checkbox" name="hobby" value="reading">
 * 		<input type="checkbox" name="hobby" value="sports">
 * 		<select name="city">
 * 			<select name="city">
 * 			<option value="bj">北京</option>
 * 			<option value="sh">上海</option>
 * 		</select>
 * </form>
 * 
 *  // 设置表单值
 * 	form.val("test-form", {
 *		username: "张三",
 *		gender: "male",
 *		hobby: ["reading", "sports"],
 *		city: "bj"
 *	});
 * 
 * // 获取表单值
 * const formData = form.val("test-form");
 * console.log(formData);
 */
var form = {
    /**
     * 获取或设置表单值
     * @param {string} filter - 表单的lay-filter值
     * @param {object} [valObj] - 可选，要设置的表单值对象
     * @returns {object} - 当不传valObj时返回表单数据对象
     */
    val: function(filter, valObj) {
        // 设置表单值
        if (valObj !== undefined) {
            return this.setValues(filter, valObj);
        }
        // 获取表单值
        else {
            return this.getValues(filter);
        }
    },
    
    /**
     * 设置表单值
     */
    setValues: function(filter, valObj) {
        const forms = document.querySelectorAll(`form[lay-filter="${filter}"]`);
        
        if (forms.length === 0) {
            console.warn(`未找到lay-filter为"${filter}"的表单`);
            return;
        }
        
        forms.forEach(form => {
            for (const key in valObj) {
                if (valObj.hasOwnProperty(key)) {
                    const elements = form.querySelectorAll(`[name="${key}"]`);
                    const value = valObj[key];
                    
                    elements.forEach(element => {
                        switch (element.type) {
                            case 'radio':
                                element.checked = (element.value === value);
                                break;
                            case 'checkbox':
                                if (Array.isArray(value)) {
                                    element.checked = value.includes(element.value);
                                } else {
                                    element.checked = (element.value === value);
                                }
                                break;
                            case 'select-one':
                            case 'select-multiple':
                                if (Array.isArray(value)) {
                                    Array.from(element.options).forEach(option => {
                                        option.selected = value.includes(option.value);
                                    });
                                } else {
                                    element.value = value;
                                }
                                break;
                            default:
                                element.value = value;
                        }
                        
                        const event = new Event('change', { bubbles: true });
                        element.dispatchEvent(event);
                    });
                }
            }
        });
    },
    
    /**
     * 获取表单值
     */
    getValues: function(filter) {
        const forms = document.querySelectorAll(`form[lay-filter="${filter}"]`);
        
        if (forms.length === 0) {
            console.warn(`未找到lay-filter为"${filter}"的表单`);
            return {};
        }
        
        // 只处理第一个匹配的表单
        const form = forms[0];
        const result = {};
        
        // 获取所有带有name属性的表单元素
        const elements = form.querySelectorAll('[name]');
        
        elements.forEach(element => {
            const name = element.name;
            
            // 如果结果对象中已有该name，说明是radio或checkbox组
            if (result.hasOwnProperty(name)) {
                return;
            }
            
            switch (element.type) {
                case 'radio':
                    // 找到选中的radio
                    const selectedRadio = form.querySelector(`[name="${name}"]:checked`);
                    result[name] = selectedRadio ? selectedRadio.value : '';
                    break;
                case 'checkbox':
                    // 处理多个checkbox
                    const checkboxes = form.querySelectorAll(`[name="${name}"]:checked`);
                    if (checkboxes.length > 1) {
                        result[name] = Array.from(checkboxes).map(cb => cb.value);
                    } else if (checkboxes.length === 1) {
                        result[name] = checkboxes[0].value;
                    } else {
                        result[name] = '';
                    }
                    break;
                case 'select-multiple':
                    // 多选下拉框返回数组
                    const selectedOptions = Array.from(element.selectedOptions);
                    result[name] = selectedOptions.map(option => option.value);
                    break;
                default:
                    // 普通输入框
                    result[name] = element.value;
            }
        });
        
        return result;
    }
};


// 使用示例：
// layer.msg('操作成功！');
// layer.confirm('确定要删除吗？', (result) => { console.log(result); });
// layer.error('操作失败！');
// layer.warn('请注意风险！');
var layer = {
    // 普通消息提示
    msg: (msg) => {
        layer.showModal(msg, '#4CAF50', 'info');
    },
    
    // 确认对话框（带回调）
    confirm: (msg, callback) => {
        const modal = layer.createModalBase(msg, '#2196F3');
        
        // 创建按钮容器
        const buttonContainer = document.createElement('div');
        buttonContainer.style.display = 'flex';
        buttonContainer.style.justifyContent = 'center';
        buttonContainer.style.marginTop = '20px';
        buttonContainer.style.gap = '10px';
        
        // 确定按钮
        const confirmBtn = document.createElement('button');
        confirmBtn.textContent = '确定';
        confirmBtn.style.padding = '8px 16px';
        confirmBtn.style.backgroundColor = '#2196F3';
        confirmBtn.style.color = 'white';
        confirmBtn.style.border = 'none';
        confirmBtn.style.borderRadius = '4px';
        confirmBtn.style.cursor = 'pointer';
        
        // 取消按钮
        const cancelBtn = document.createElement('button');
        cancelBtn.textContent = '取消';
        cancelBtn.style.padding = '8px 16px';
        cancelBtn.style.backgroundColor = '#f5f5f5';
        cancelBtn.style.color = '#333';
        cancelBtn.style.border = '1px solid #ddd';
        cancelBtn.style.borderRadius = '4px';
        cancelBtn.style.cursor = 'pointer';
        
        // 添加按钮到容器
        buttonContainer.appendChild(confirmBtn);
        buttonContainer.appendChild(cancelBtn);
        
        // 添加按钮容器到模态框
        modal.appendChild(buttonContainer);
        
        // 按钮事件
        confirmBtn.onclick = () => {
            document.body.removeChild(modal);
            if (callback) callback(true);
        };
        
        cancelBtn.onclick = () => {
            document.body.removeChild(modal);
            if (callback) callback(false);
        };
    },
    
    // 错误提示
    error: (msg) => {
        layer.showModal(msg, '#f44336', 'error');
    },
    
    // 警告提示
    warn: (msg) => {
        layer.showModal(msg, '#ff9800', 'warning');
    },
	// 创建基础模态框
	createModalBase:(msg, color) => {
        const modal = document.createElement('div');
        modal.style.position = 'fixed';
        modal.style.top = '0';
        modal.style.left = '0';
        modal.style.width = '100%';
        modal.style.height = '100%';
        modal.style.backgroundColor = 'rgba(0,0,0,0.5)';
        modal.style.display = 'flex';
        modal.style.justifyContent = 'center';
        modal.style.alignItems = 'center';
        modal.style.zIndex = '9999';
        
        const content = document.createElement('div');
        content.style.backgroundColor = 'white';
        content.style.padding = '9px';
        content.style.borderRadius = '8px';
        content.style.boxShadow = '0 4px 12px rgba(0,0,0,0.15)';
        content.style.maxWidth = '80%';
        content.style.minWidth = '100px';
        content.style.textAlign = 'center';
        
        // 标题
        const title = document.createElement('div');
        title.textContent = msg;
        title.style.marginBottom = '9px';
        title.style.fontSize = '16px';
        title.style.color = '#333';
        
        content.appendChild(title);
        modal.appendChild(content);
        document.body.appendChild(modal);
        
        return content;
    },
	// 显示自动关闭的模态框
	showModal: (msg, color, type)  => {
		const content = layer.createModalBase(msg, color);
		
		// 添加图标
		const icon = document.createElement('div');
		icon.style.fontSize = '20px';
		icon.style.marginBottom = '6px';
		
		switch(type) {
		    case 'info':
		        icon.textContent = 'ℹ️';
		        break;
		    case 'error':
		        icon.textContent = '❌';
		        break;
		    case 'warning':
		        icon.textContent = '⚠️';
		        break;
		    default:
		        icon.textContent = 'ℹ️';
		}
		
		content.insertBefore(icon, content.firstChild);
		
		// 自动关闭
		var temMsgIndex = null;
		setTimeout(() => {
		    content.parentElement.style.transition = 'opacity 0.3s';
		    content.parentElement.style.opacity = '0';
		    temMsgIndex = setTimeout(() => {
				try {
					document.body.removeChild(content.parentElement);
				} catch (error) {
					//TODO handle the exception
				}
		    }, 300);
		}, 1500);
		 // 添加点击事件：点击遮罩层关闭弹窗
		content.parentElement.addEventListener('click', (e) => {
			if (e.target === content.parentElement) { // 确保点击的是遮罩层，而不是内容区域
				document.body.removeChild(content.parentElement);
				if(temMsgIndex || temMsgIndex === 0){
					clearTimeout(temMsgIndex);
				}
			}
		});
	},
};
